<template>
  <div id="app">
    <div class="header">
      <el-input
        v-model="topicInput"
        placeholder="搜索用户名"
        clearable
        style="width: 200px; margin-right: 10px"
        @keyup.enter="handleSearch"
      />
      <el-button type="primary" icon="el-icon-search" @click="handleSearch">
        搜索
      </el-button>

      <el-select
        v-model="timeFilter"
        placeholder="选择时间"
        style="width: 140px; margin-left: 10px"
        @change="handleTimeFilterChange"
      >
        <el-option label="全部" value="all" />
        <el-option label="指定日期" value="custom" />
      </el-select>

      <el-date-picker
        v-if="timeFilter === 'custom'"
        v-model="customDate"
        type="date"
        placeholder="选择日期"
        style="margin-left: 10px"
        @change="handleDateChange"
      />
    </div>

    <div class="content">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        header-align="center"
        style="width: 100%"
      >
        <!-- <el-table-column type="selection" width="100" align="center" /> -->
        <el-table-column label="用户名" align="center" width="350">
          <template #default="{ row }">{{ row.user?.username }}</template>
        </el-table-column>
        <el-table-column label="题目数" align="center" width="200">
          <template #default="{ row }">{{ row.content?.length || 0 }}</template>
        </el-table-column>
        <el-table-column label="完成度(%)" align="center" width="200">
          <template #default="{ row }">{{ row.finishedPercent }}%</template>
        </el-table-column>
        <el-table-column label="正确率(%)" align="center" width="200">
          <template #default="{ row }">{{ row.accuracyPercent }}%</template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="200">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row)">{{ getStatusText(row) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="created_at"
          label="答题时间"
          align="center"
          width="350"
        >
          <template #default="{ row }">{{ formatDate(row.created_at) }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button type="text" size="mini" @click="openDetail(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 16px; text-align: center"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

      <el-dialog
        :visible.sync="detailDialogVisible"
        title="答题详情"
        width="60%"
      >
        <el-table
          :data="currentDetail"
          border
          header-align="center"
          style="width: 100%"
        >
          <el-table-column label="序号" width="80" align="center">
            <template #default="{ $index }">{{ $index + 1 }}</template>
          </el-table-column>
          <el-table-column label="题目" align="center">
            <template #default="{ row }">
              {{ row.topic || row.topic_id || "无题干" }}
            </template>
          </el-table-column>
          <el-table-column label="选项" width="350" align="center">
            <template #default="{ row }">
              <div class="option-grid">
                <div
                  v-for="(option, index) in row.content"
                  :key="option.id || index"
                >
                  <span
                    :style="{
                      color: option.is_ok === 1 ? 'green' : 'inherit',
                      fontWeight: option.is_ok === 1 ? 'bold' : 'normal'
                    }"
                  >
                    {{ getOptionLetter(index) }}. {{ option.content }}
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="正确答案" width="100" align="center">
            <template #default="{ row }">
              <span style="color: green; font-weight: bold">
                {{ getCorrectAnswer(row) }}
              </span>
            </template>
          </el-table-column>

          <el-table-column label="用户答案" width="100" align="center">
            <template #default="{ row }">
              <span
                :style="{
                  color: isAnswerCorrect(row) ? 'green' : 'red',
                  fontWeight: 'bold'
                }"
              >
                {{ getUserAnswer(row) }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { examRecord } from '@/api/question'
import { getAllUser } from '@/api/v2/personnel'

export default {
  name: 'AnswerRecordList',
  data() {
    return {
      tableData: [],
      page: 1,
      pageSize: 10,
      total: 0,
      topicInput: '',
      timeFilter: null,
      customDate: null,
      loading: false,
      detailDialogVisible: false,
      currentDetail: []
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleTimeFilterChange(value) {
      if (value !== 'custom') {
        this.customDate = null
      }
      this.page = 1
      this.fetchData()
    },

    handleDateChange() {
      this.page = 1
      this.fetchData()
    },

    async fetchData() {
      this.loading = true
      let userId = null

      // 如果输入了用户名，先查 user_id
      if (this.topicInput) {
        try {
          const res = await getAllUser({
            username: this.topicInput
          })
          if (res?.data?.length) {
            userId = res.data[0].id
          } else {
            this.$message.warning('未找到该用户')
            this.tableData = []
            this.total = 0
            this.loading = false
            return
          }
        } catch (e) {
          console.error('getAllUser error:', e)
          this.$message.error('查询用户失败')
          this.loading = false
          return
        }
      }

      // 时间筛选
      let timeParam = ''
      if (this.timeFilter === 'custom' && this.customDate) {
        const d = this.customDate
        const Y = d.getFullYear()
        const M = String(d.getMonth() + 1).padStart(2, '0')
        const D = String(d.getDate()).padStart(2, '0')
        timeParam = `${Y}-${M}-${D}`
      }

      try {
        const res = await examRecord({
          user_id: userId,
          time: timeParam,
          page: this.page,
          pageSize: this.pageSize
        })
        const records = res.data.data || []

        const processedRecords = records.map((record) => {
          const totalQuestions = record.content ? record.content.length : 0
          let finishedCount = 0
          let correctCount = 0

          if (record.content && Array.isArray(record.content)) {
            record.content.forEach((topic) => {
              if (topic.answer_info?.user_answer) {
                finishedCount++
                if (topic.answer_info.is_true === 1) {
                  correctCount++
                }
              }
            })
          }

          const finishedPercent =
            totalQuestions > 0
              ? ((finishedCount / totalQuestions) * 100).toFixed(0)
              : 0
          const accuracyPercent =
            finishedCount > 0
              ? ((correctCount / finishedCount) * 100).toFixed(0)
              : 0

          return {
            ...record,
            finishedPercent: parseFloat(finishedPercent),
            accuracyPercent: parseFloat(accuracyPercent)
          }
        })

        this.tableData = processedRecords
        this.total = res.data.total
      } catch (err) {
        this.$message.error('获取考试记录失败')
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.page = 1
      this.fetchData()
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.page = 1
      this.fetchData()
    },

    handleCurrentChange(val) {
      this.page = val
      this.fetchData()
    },

    formatDate(utcString) {
      if (!utcString) return ''
      const date = new Date(utcString)
      const Y = date.getFullYear()
      const M = String(date.getMonth() + 1).padStart(2, '0')
      const D = String(date.getDate()).padStart(2, '0')
      const h = String(date.getHours()).padStart(2, '0')
      const m = String(date.getMinutes()).padStart(2, '0')
      const s = String(date.getSeconds()).padStart(2, '0')
      return `${Y}-${M}-${D} ${h}:${m}:${s}`
    },

    getStatusText(row) {
      if (row.finishedPercent >= 0 && row.finishedPercent < 100) return '未完成'
      if (row.finishedPercent === 100) return '已完成'
      return '未知'
    },

    getStatusType(row) {
      if (row.finishedPercent >= 0 && row.finishedPercent < 100) return 'warning'
      if (row.finishedPercent === 100) return 'success'
      return 'info'
    },

    getOptionLetter(index) {
      return String.fromCharCode(65 + index)
    },

    getCorrectAnswer(row) {
      if (!row.content) return ''
      return row.content
        .map((opt, i) => (opt.is_ok === 1 ? this.getOptionLetter(i) : null))
        .filter(Boolean)
        .join(',')
    },

    getUserAnswer(row) {
      const userRaw = row.answer_info?.user_answer
      if (!userRaw) return ''
      const ids = String(userRaw)
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean)
      return ids
        .map((id) => {
          const idx = (row.content || []).findIndex(
            (opt) => String(opt.id) === id
          )
          return idx >= 0 ? this.getOptionLetter(idx) : id
        })
        .join(',')
    },

    isAnswerCorrect(row) {
      const userAnswer = this.getUserAnswer(row).split(',')
      const correctAnswer = this.getCorrectAnswer(row).split(',')
      if (userAnswer.length !== correctAnswer.length) return false
      return userAnswer.every((a) => correctAnswer.includes(a))
    },

    openDetail(row) {
      this.currentDetail = row.content || []
      this.detailDialogVisible = true
    }
  }
}
</script>

<style scoped lang="scss">
#app {
  padding: 20px;
}

.header {
  background-color: #fff;
  margin-bottom: 20px;
  padding: 10px;
  display: flex;
  align-items: center;
}

.content {
  background-color: #fff;
  padding: 20px;
}

.option-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 4px 8px;
}
</style>
